import fs from 'fs'
import path from 'path'
import { parse, stringify } from 'yaml'
import { ConfManager } from './manager'

const getKey = (conf, key) => {
  const keys = key.split('.')
  let res = ''
  if (keys.length > 1) {
    let val = conf
    keys.forEach(k => {
      if (val[k]) val = val[k]
    })
    res = val
  } else {
    res = conf[key]
  }
  console.log(`conf[${key}] ==> ${res}`)
  return res
}

const setConf = (app) => {
  const rootDir = path.join(__dirname, '../../')
  const confFile = fs.readFileSync(`${rootDir}/conf.yaml`, 'utf-8')
  const confJson = parse(confFile)
  // app.locals.conf = confJson
  ConfManager.addToState('conf', confJson)
}

export default setConf

export const get = (key) => {
  // const conf = app.locals.conf
  const conf = ConfManager.readFromState('conf')
  return getKey(conf, key)
}
